package cn.dianhun.om.jpa.controller.testcrud;


import cn.dianhun.om.jpa.pojo.PersonEntity;
import cn.dianhun.om.jpa.repository.PersonRepository;
import cn.dianhun.om.jpa.utills.ResultVO;
import cn.dianhun.om.jpa.utills.ResultVOUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @author cyt
 * @create 2020-07-10 10:16
 */

@RequestMapping("/test/api")
@Slf4j
@RestController
public class testCrudController {
    @Autowired
    private PersonRepository personRepository;

    @PostMapping("/insert")
    public void insert() {
        for (int i = 0; i < 30; i++) {
            PersonEntity person = new PersonEntity();
            person.setName("name" + UUID.randomUUID().toString().substring(0, 2)).setId(i).setAddress("address" + UUID.randomUUID().toString().substring(0, 2));
            personRepository.save(person);
        }
    }

    @GetMapping("/getTestData")
    public ResultVO getTestData() {
        List<PersonEntity> personList = personRepository.findAll();
        log.info("list" + personList.toString());
        return ResultVOUtil.successWith(personList);
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public ResultVO delete(@PathVariable("id") Integer id) {
        personRepository.deleteById(id);
        return ResultVOUtil.success();
    }


    /**
     * 安装 id 查询
     *
     * @param id
     * @return
     */
    @GetMapping("/getById/{id}")
    public ResultVO getById(@PathVariable("id") Integer id) {
        Optional<PersonEntity> byId = personRepository.findById(id);
        PersonEntity entity = byId.get();
        return ResultVOUtil.successWith(entity);
    }


    /**
     * 保存
     *
     * @param personEntity
     * @return
     */

    @PostMapping("/save")
    public ResultVO save(@RequestBody PersonEntity personEntity) {
        personRepository.save(personEntity);
        return ResultVOUtil.success();
    }


    /**
     * 更新
     *
     * @param personEntity
     * @return
     */
    @PostMapping("/update")
    public ResultVO update(@RequestBody PersonEntity personEntity) {
        Optional<PersonEntity> byId = personRepository.findById(personEntity.getId());
        BeanUtils.copyProperties(personEntity, byId.get());
        personRepository.save(byId.get());
        return ResultVOUtil.success();
    }


    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/query/{page}/{size}")
    public ResultVO query(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        Page<PersonEntity> repositoryAll = personRepository.findAll(getPage(page, size));
        return ResultVOUtil.successWith(repositoryAll);
    }

    static Pageable getPage(Integer page, Integer size) {
        Pageable of = PageRequest.of(
                page - 1, size,
                Sort.by(Sort.Direction.ASC, "id")
        );
        return of;
    }


    /**
     * 条件分页查询
     *
     * @param page
     * @param size
     * @param person
     * @return
     */

    @PostMapping("/queryVo/{page}/{size}")
    public ResultVO queryVo(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @RequestBody PersonEntity person) {
        log.info("search info:  " + person.toString());

        Specification<PersonEntity> specification = (Specification<PersonEntity>) (root, query, builder) -> {

            List<Predicate> predicateList = new ArrayList<>();
            if (!StringUtils.isEmpty(person.getName())) {
                predicateList.add(builder.like(root.get("name"),
                        "%" + StringUtils.trimWhitespace(person.getName()) + "%"));
            }
            if (!StringUtils.isEmpty(person.getAddress())) {
                predicateList.add(builder.like(root.get("address"),
                        "%" + StringUtils.trimWhitespace(person.getAddress()) + "%"));
            }
            return builder.and(predicateList.toArray(new Predicate[0]));
        };

        Page<PersonEntity> repositoryAll = personRepository.findAll(specification, getPage(page, size));
        return ResultVOUtil.successWith(repositoryAll);
    }


}

